package bookstudytest.threadtest.threadmethod;

import bookstudytest.threadtest.implement.ThreadByRunnable;

/**
 * @author heng.li
 * join 方法可以使一个线程优先执行，线程a中使用线程b的join方法，就会优先执行完毕线程b的逻辑
 * wait是Object的方法，而sleep是Thread的静态方法，wait会释放锁，重新获得锁后还是会根据cpu时间分片去执行，不会立即执行
 * 而sleep不是释放锁，时间一到就会立即执行
 * 执行wait方法后，线程被挂起，等待其它线程调用notify和notifyAll方法来唤醒挂起的线程
 * wait只能用在同步方法或者同步控制块中使用
 */
public class JoinTest implements Runnable {
    private Thread thread;

    public JoinTest(Thread thread) {
        this.thread = thread;
    }

    @Override
    public void run() {
        try {
            this.thread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("here we are ");
    }

    public static void main(String[] args) {
        ThreadByRunnable threadByRunnable = new ThreadByRunnable();
        Thread thread1 = new Thread(threadByRunnable);
        JoinTest joinTest = new JoinTest(thread1);
        Thread thread = new Thread(joinTest);
        try {
            thread.wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        thread.notify();
        thread.start();
        thread1.start();
    }
}
